package com.delayqueue.registry.netty.bootstrap;

import com.delayqueue.common.netty.handler.*;
import com.delayqueue.registry.netty.handler.ConnectInBoundHandler;
import com.delayqueue.registry.netty.handler.MessageInBoundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RegistryBootstrap {

    public void init() {
        log.info("正在启动注册中心");
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, work);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {

                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast(new StringToByteEncoder());
                pipeline.addLast(new MessageToStringEncoder());

                pipeline.addLast(new ConnectInBoundHandler());
                pipeline.addLast(new ByteToStringDecoder());
                pipeline.addLast(new StringToMessageHandler());
                pipeline.addLast(new MessageInBoundHandler());
                pipeline.addLast(new ExceptionHandler());
            }
        });
        serverBootstrap.bind(8888);
        log.info("注册中心启动成功");
    }
}
